package com.example.driving.utils;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChatGPTRequest extends AsyncTask<String, Void, String> {

    public static final String MODEL = "model";
    private static final String API_URL = "https://api.openai.com/v1/chat/completions"; // 替换为实际的API URL

    // 替换为实际的 OpenAI API Key
    String apiKey = "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";

    String message;

    private OnResponseReceivedListener onResponseReceivedListener;

    String re_content;



    public String getMessage() {
        return message;
    }

    @Override
    protected String doInBackground(String... params) {

        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < params.length; i++) {
            stringBuilder.append(params[i]);
        }
        String result = stringBuilder.toString();

        try {
        // 创建 OkHttpClient 实例
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(600, TimeUnit.SECONDS) // 增加连接超时时间
                    .readTimeout(600, TimeUnit.SECONDS) // 增加读取超时时间
                    .writeTimeout(600, TimeUnit.SECONDS) // 增加写入超时时间
                    .build();

        // 构建请求体数据
        System.out.println("// 构建请求体数据");
        JSONArray messagesArray = new JSONArray();
        JSONObject messageObject = new JSONObject();

        messageObject.put("role", "user");
            System.out.println("params---->");
            System.out.println(result);
        messageObject.put("content", result);
        messagesArray.put(messageObject);

        JSONObject requestBody = new JSONObject();
        requestBody.put(MODEL, "gpt-3.5-turbo");
        requestBody.put("messages", messagesArray);



        // 创建请求对象
        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("Authorization", "Bearer " + apiKey) 
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .post(RequestBody.create(MediaType.parse("application/json"), requestBody.toString()))
                .build();


        // 发送请求并处理响应
            System.out.println("// 发送请求并处理响应");
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {

                String responseData = response.body().string();
                System.out.println("-------------responseData");
                System.out.println(responseData);


                // 处理来自 ChatGPT 的响应数据
                JSONObject responseJson = new JSONObject(responseData);
                JSONArray choicesArray = responseJson.getJSONArray("choices");
                JSONObject choiceObject = choicesArray.getJSONObject(0);
                JSONObject re_messageObject = choiceObject.getJSONObject("message");
                re_content = re_messageObject.getString("content");


                // 在这里处理来自 ChatGPT 的回复
                System.out.println("在这里处理来自 ChatGPT 的回复");
                System.out.println(re_content);
                return re_content;
            } else {
                // 处理请求失败的情况
                System.out.println("HTTP error code: " + response.code());
                return re_content;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void setOnResponseReceivedListener(OnResponseReceivedListener listener) {
        onResponseReceivedListener = listener;
    }

    protected void onPostExecute(String response) {
        // 在这里处理网络请求的响应


        if (response != null) {
            if (onResponseReceivedListener != null) {
                onResponseReceivedListener.onResponseReceived(re_content);
            }
            Log.d("ChatGPTResponse------->", re_content);
        } else {
            Log.e("ChatGPTResponse-------->", "No response received");
        }
    }



}
